import React from 'react';
import { Result, Button } from 'antd';
import { useNavigate } from 'react-router-dom';

// 权限配置
const PERMISSIONS = {
  SUPER_ADMIN: {
    role: '超级管理员',
    allowedPages: ['home', 'course', 'student', 'teacher', 'orders', 'refunds', 'banner', 'article', 'flash-sale', 'coupon', 'settings'],
    allowedActions: ['view', 'add', 'edit', 'delete', 'manage_teachers']
  },
  TEACHER: {
    role: '教师',
    allowedPages: ['home', 'course', 'student', 'teacher', 'settings', 'schedule'],
    allowedActions: ['view', 'edit', 'add', 'delete', 'manage_students', 'manage_courses'],
    restrictedActions: ['manage_teachers', 'manage_orders', 'manage_dashboard']
  }
};

// 获取用户权限
export const getUserPermissions = (userId) => {
  if (!userId) return null;
  
  if (userId.startsWith('100')) {
    return PERMISSIONS.SUPER_ADMIN;
  } else if (userId.startsWith('200')) {
    return PERMISSIONS.TEACHER;
  }
  
  return null;
};

// 检查页面访问权限
export const checkPagePermission = (userId, pageKey) => {
  const permissions = getUserPermissions(userId);
  if (!permissions) return false;
  
  return permissions.allowedPages.includes(pageKey);
};

// 检查操作权限
export const checkActionPermission = (userId, action) => {
  const permissions = getUserPermissions(userId);
  if (!permissions) return false;
  
  // 检查是否被限制的操作
  if (permissions.restrictedActions && permissions.restrictedActions.includes(action)) {
    return false;
  }
  
  return permissions.allowedActions.includes(action);
};

// 权限守卫组件
export default function PermissionGuard({ children, pageKey, userId, fallback = null }) {
  const navigate = useNavigate();
  
  // 检查权限
  if (!checkPagePermission(userId, pageKey)) {
    if (fallback) {
      return fallback;
    }
    
    return (
      <Result
        status="403"
        title="403"
        subTitle="抱歉，您没有权限访问此页面。"
        extra={
          <Button type="primary" onClick={() => navigate('/houtai')}>
            返回首页
          </Button>
        }
      />
    );
  }
  
  return children;
}

// 操作权限守卫组件
export function ActionPermissionGuard({ children, action, userId, fallback = null }) {
  if (!checkActionPermission(userId, action)) {
    return fallback || null;
  }
  
  return children;
} 